package xyz.xiaoshengfu.xrpc.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import xyz.xiaoshengfu.xrpc.consumer.XRpcConsumerInvokeClient;

/**
 * <p>Title: RPCProxyClient</p>
 * <p>Description: 接口代理</p>
 * @author xiaoshengfu(2439323118@qq.com)
 * @date 2020年2月27日
 */
public class XRpcProxyClient implements InvocationHandler {

	private String fullyQualifiedClassName;

	public XRpcProxyClient(String fullyQualifiedClassName) {
		this.fullyQualifiedClassName = fullyQualifiedClassName;
	}

	public String getFullyQualifiedClassName() {
		return fullyQualifiedClassName;
	}

	/**
	 * 调用此方法执行
	 */
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		return XRpcConsumerInvokeClient.invokeRemoteMethod(fullyQualifiedClassName, method.getName(), args)
				.getReturnValue();
	}

	public static Object invokeMethod(Object methodObject, String methodName, Object[] args) throws Exception {
		Class<?> ownerClass = methodObject.getClass();
		Class<?>[] argsClass = new Class[args.length];
		for (int i = 0, j = args.length; i < j; i++) {
			argsClass[i] = args[i].getClass();
		}
		Method method = ownerClass.getMethod(methodName, argsClass);
		return method.invoke(methodObject, args);
	}
}